<?php 

include_once 'site_config.php';
include_once 'ra_global1.php';
define("TOKEN", "rams1234");
define("SELLSCORE", 15);


$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg($db);

class wechatCallbackapiTest{
	public function valid(){
		$echoStr = $_GET["echostr"];
		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
		
	
	}
	//接口数据写日志方法
	public function _log($data){
		$logfile = 'log.txt';
		$file = fopen($logfile,'a+');
		if(is_string($data)){
			$dataStr = '【Sting】'.$data;
		}elseif(is_array($data)){
			$dataStr = '【Array】'.json_encode($data,JSON_UNESCAPED_UNICODE);
		}elseif(is_object($data)){
			$dataStr = '【Object】'.json_encode($this->_object_to_array($data));
		}else{
			$dataStr = '【Unknow Type】'.$data;
		}
		$dataStr = date('Ymd_His').$dataStr.''; 
		fwrite($file,$dataStr);
		fclose(); 
	}
	
	public function _object_to_array($obj){
	    $_array = is_object($obj) ? get_object_vars($obj) : $obj;
	    foreach ($_array as $key => $v) {
	        $v = (is_array($v) || is_object($v)) ? _object_to_array($v) : $v;
	        $array[$key] = $v;
	    }
	    return $array;
	}

	public function responseMsg($db){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		
	  	//extract post data
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$this->fromUsername = $postObj->FromUserName;
			$this->toUsername = $postObj->ToUserName;
			$ticket = $postObj->Ticket;
			$event = $postObj->Event;
			$eventKey = trim($postObj->EventKey);
			$MsgType=trim($postObj->MsgType);
			$url= SiteUrl.'reg.php';
			$picurl=SiteUrl.'shopcode/90001.jpg';
			$des='';
			if($MsgType=='event'){
				//事件处理
				switch($event){
					case 'scancode_waitmsg':
						//自定义菜单扫描等待消息
						if($eventKey === 'scanoil'){
                            $ScanResult=$postObj->ScanCodeInfo->ScanResult;
                            $ScanResult=explode('?',$ScanResult);
                            if(sizeof($ScanResult)==2){
                                $ScanResult=$ScanResult[1];
                                $ScanResult=substr($ScanResult,1,16);
                                if(is_numeric($ScanResult) && strlen($ScanResult)==16) {
                                    $this->sendTxt($this->getScanResult($db, $this->fromUsername, $ScanResult));
                                }
                            }

//							//扫码验证
//							$user=$db->ig2_want('mae_user','role_type=2 and openid="'.$this->fromUsername.'"');
//							if(!$user){
//								//扫描人不是店员
//								$this->sendTxt('只有店员可以参与扫油积分活动，您无法参与此积分活动');
//							}
//							$role=$db->ig2_want('mae_role','is_delete=0 and role_type=2 and uid='.$user['id']);
//							if(!$role){
//								//扫描人不是店员
//								$this->sendTxt('只有店员可以参与扫油积分活动，您无法参与此积分活动');
//							}
//							$ScanResult=$postObj->ScanCodeInfo->ScanResult;
//							$ScanResult=explode('?',$ScanResult);
//							if(sizeof($ScanResult)==2){
//								$ScanResult=$ScanResult[1];
//								$ScanResult=substr($ScanResult,1,16);
//								if(is_numeric($ScanResult) && strlen($ScanResult)==16){
//									//正常获得16位数字产品编码
//									$client = new SoapClient(API_url);
//									$param = array(
//										'userID'=>API_userID,
//										'userPwd'=>API_userPwd,
//										'ip'=>$this->GetIP(),
//										'acCode'=>$ScanResult,
//										'language'=>'zh-cn',
//										'channel'=>'21'
//									);
//									$p = $client->__soapCall('Get_ACCodeProductInfo',array('parameters' => $param));
//									$state=$p->systemState;
//									$state=substr($state,0,4);
//									switch($state){
//										case '1002':
//											//数码存在
//											$sell=$db->ig2_want('mae_sell','shell_key="'.$ScanResult.'"');
//											if($sell){
//												//已售出
//												$this->sendTxt('此商品已售出');
//											}else{
//												//未售出
//												$reply=$p->reply;
//												$reply = simplexml_load_string($reply, 'SimpleXMLElement', LIBXML_NOCDATA);
//												if($reply->item->productid=='' && ($reply->item->productspec=='小桶(3.5L-5L)'||$reply->item->productspec=='1L-5L'||$reply->item->productspec=='4L')){
//													$reply->item->productid=550000000;
//												}
//												$pro=$db->ig2_want('mae_pro','pro_id="'.$reply->item->productid.'"');
//												$p->reply=$reply;
//												$p=json_encode($p);
//												if($pro){
//													//是活动商品
//													$co=0;
//													$succes=false;
//													while(!$succes){
//														$succes=true;
//														$id=0;
//														$db->ig2_query('BEGIN');
//														//插入销售记录
//														$result1=$db->ig2_query("insert into mae_sell (`id`,`account_id`,`shell_key`,`pro_id`,`productname`,`productspec`,`productinfo`,`uid`,`create_time`) values ('".$id."','16621','".$ScanResult."','".$reply->item->productid."','".$reply->item->productname."','".$reply->item->productspec."','".$p."','".$user['id']."','".time()."');");
//														$succes=$succes && $result1?true:false;
//														//更新积分
//														$result2=$db->ig2_query("update mae_user set score=".($user['score']+SELLSCORE)." WHERE id=".$user['id']);
//														$succes=$succes && $result2?true:false;
//														$result3=$db->ig2_query("update mae_shop set sell_count=sell_count+1,now_month_count=now_month_count+1,quadratic=quadratic+".SELLSCORE." WHERE id=".$role['shop_id']);
//														$succes=$succes && $result3?true:false;
//														//插入心愿单
//														$sday=date('Y-m-',time()).'1';
//														$eday=date('Y-m-d',strtotime("$sday +1 month"));
//														$sday=strtotime($sday);
//														$eday=strtotime($eday);
//														$lastwish=$db->ig2_select("mae_wish_list","uid=".$user['id']." and create_time >= $sday and create_time < $eday");
//														if(!$lastwish){
//															$succes=$succes && $db->ig2_query("insert into mae_wish_list (`account_id`,`sell_id`,`uid`,`status`,`is_see`,`create_time`) values ('16621','".$ScanResult."','".$user['id']."','0','0','".time()."');")?true:false;
//															$wishid=mysql_insert_id();
//														}
//														if($succes){
//															$db->ig2_query('COMMIT');
//														}else{
//															$db->ig2_query('ROLLBACK');
//														}
//														if(++$co>=100){
//															$this->sendTxt('服务器忙，请稍后再试('.$result1.'0'.$result2.'0'.$result3);
//														}
//													}
//													$this->sendTxt('验证成功，成功获得15个积分，可在个人中心查看并兑换'.($wishid?'，并可填写<a href="'.SiteUrl.'wish.php?wishid='.$wishid.'">心愿单</a>':''));
//												}else{
//													//非活动商品
//													$this->sendTxt('此商品为真，但不在活动商品之列');
//												}
//											}
//											break;
//										case '0002':
//											//数码不存在
//											$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
//											break;
//										case '003':
//											//数码不存在
//											$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
//											break;
//										case '102':
//											//数码不存在
//											$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
//											break;
//										default:
//											//ip限制，ip最大值等问题
//											$this->sendTxt('查询异常');
//											break;
//									}
//									exit;
//								}
//							}
//							//未获得16位数字产品编码
//							$this->sendTxt('错误二维码,若您想绑定店长或店员请在微信消息列表界面点右上角加号选扫一扫扫描二维码');
						}else{
							//非扫码验证
						}
						break;
					case 'SCAN':
						//扫描带参数的二维码
						$user=$db->ig2_want('mae_user','openid="'.$this->fromUsername.'" and is_delete=0');
						if($user){
							//用户已存在
							$this->sendTxt('您已经有店铺，不能重复绑定');
						}else{
							//是店长二维码
							$shop=$db->ig2_want('mae_shop','(code="'.$eventKey.'" or tid="'.$eventKey.'") and status=1');
							if($shop){
								//店铺存在
								if($shop['tid']==$eventKey){
									if($shop['is_activate']==1){
										//已激活
										$this->sendTxt('此店铺已有店长，不能重复绑定');
									}else{
										//未激活
										$activeshops=$db->ig2_select('mae_shop','is_activate=1 and city_id='.$shop['city_id'].' and status=1');
										$city=$db->ig2_want('mae_city','id='.$shop['city_id']);
										if(sizeof($activeshops)>=$city['limit']){
											$this->sendTxt('该城市已达到绑定上限，不能绑定新店');
										}else{
											//未达到城市上线
											$title='点击进入完成店长注册';
											$url=$url.'?type=1&tid='.$shop['tid'].'&openid='.$this->fromUsername;
											$this->sendNews($title,$des,$picurl,$url);
										}
									}
								}elseif($shop['code']==$eventKey){
									$users=$db->ig2_select('mae_role','is_delete=0 and role_type=2 and shop_id='.$shop['id']);
									if((sizeof($users))>=($shop['repairman_limit']+$shop['salesman_limit']))	$this->sendTxt('该店店员已达到上限');
									else{
										$title='点击进入完成店员注册';
										$url=$url.'?type=2&regtime='.time().'&tid='.$shop['tid'].'&openid='.$this->fromUsername;
										$des='请在15分钟内完成注册，超时需重新扫码。';
										$this->sendNews($title,$des,$picurl,$url);
									}
								}
							}else{
								//店铺不存在
								$this->sendTxt('店铺不存在');
							}
						}					
						break;
					case 'subscribe':
						$eventKey=explode('_',$eventKey);
						if($eventKey[0]=='qrscene'){
							//扫描带参数的二维码
							$eventKey=$eventKey[1];
							$user=$db->ig2_want('mae_user','openid="'.$this->fromUsername.'" and is_delete=0');
							if($user){
								//用户已存在
								$this->sendTxt('您已经有店铺，不能重复绑定');
							}else{
								//是店长二维码
								$shop=$db->ig2_want('mae_shop','(code="'.$eventKey.'" or tid="'.$eventKey.'") and status=1');
								if($shop){
									//店铺存在
									if($shop['tid']==$eventKey){
										if($shop['is_activate']==1){
											//已激活
											$this->sendTxt('此店铺已有店长，不能重复绑定');
										}else{
											//未激活
											$activeshops=$db->ig2_select('mae_shop','is_activate=1 and city_id='.$shop['city_id'].' and status=1');
											$city=$db->ig2_want('mae_city','id='.$shop['city_id']);
											if(sizeof($activeshops)>=$city['limit']){
												$this->sendTxt('该城市已达到绑定上限，不能绑定新店');
											}else{
												//未达到城市上线
												$title='点击进入完成店长注册';
												$url=$url.'?type=1&tid='.$shop['tid'].'&openid='.$this->fromUsername;
												$this->sendNews($title,$des,$picurl,$url);
											}
										}
									}elseif($shop['code']==$eventKey){
										$users=$db->ig2_select('mae_role','is_delete=0 and role_type=2 and shop_id='.$shop['id']);
										if((sizeof($users))>=($shop['repairman_limit']+$shop['salesman_limit']))	$this->sendTxt('该店店员已达到上限');
										else{
											$title='点击进入完成店员注册';
											$url=$url.'?type=2&regtime='.time().'&tid='.$shop['tid'].'&openid='.$this->fromUsername;
											$des='请在15分钟内完成注册，超时需重新扫码。';
											$this->sendNews($title,$des,$picurl,$url);
										}
									}
								}else{
									//店铺不存在
									$this->sendTxt('店铺不存在');
								}
							}	
						}
						else
							$this->sendTxt('欢迎');
						break;
					case 'CLICK':
						switch($eventKey){
                            case 'jifenhongbao':
                                //$this->sendTxt('积分红包会不定期发放，发放时会通过个人中心通知，敬请期待！');
                                $this->pushRedPocket($db, $this->fromUsername);
                                break;
                            // 去除手动输入序列号事件
							case 'writeoil':
								$this->sendTxt('请点击左下角键盘图标输入瓶盖处序列号');
								break;
							case 'readme':
								$this->sendTxt('验证积分方法：
方法一： 您可输入油桶盖上的16位号码验证积分；
方法二： 您可扫描二维码验证积分；
 
验证积分小贴士：
若验证失败，请参考以下原因耐心检查后重新输入：
1. 是否输入了错的数码（缺少或多输入一位）；
2. 您的验证码是否已被使用；
3. 您是否输入了已失效的验证码；

备注：
1.壳牌喜力超凡大师是壳牌资助的一项市场促销活动。门店基于自愿原则参加活动，参与店员也由门店自行决定。
2.此活动解释权归属壳牌，活动机制可能更改，如有更改会与门店沟通,  门店可自行决定是否继续参加。
');
								break;
//							case 'cheapcode':
//								$this->sendTxt('请点击左下角键盘图标，输入滚雪球卡券序列号。');
//								break;
							default:
								$this->sendTxt('');
								break;
						}
						break;
					default:
						$this->sendTxt('');
						break;
				}
			}elseif($MsgType=='text'){
                $Content=trim($postObj->Content);
                if (is_numeric($Content) && strlen($Content)==16) {
                    $this->sendTxt($this->getScanResult($db, $this->fromUsername, $Content));
                }

                // 去除手输序列号的微信事件
//				$Content=trim($postObj->Content);
//				if(is_numeric($Content) && strlen($Content)==18){
//					$cheap_code=$db->ig2_want('mae_cheap_code','code='.$Content);
//					if($cheap_code){
//						if($cheap_code['count']<=$cheap_code['get_count']){
//							$this->sendTxt('此代码使用已超过规定次数，请输入新码');
//						}else{
//							$value=array('get_count'=>$cheap_code['get_count']+1);
//							$db->ig2_update('mae_cheap_code',$value,'id='.$cheap_code['id']);
//							$user=$db->ig2_want('mae_user,mae_role','mae_role.is_delete=0 and mae_user.id=mae_role.uid and mae_user.openid="'.$this->fromUsername.'"');
//							$value=array(
//								'id'			=>'',
//								'account_id'	=>16621,
//								'cheap_id'		=>$cheap_code['id'],
//								'shop_id'		=>$user['shop_id'],
//								'uid'			=>$user['uid'],
//								'create_time'	=>time()
//							);
//							$db->ig2_insert('mae_cheap_code_log',$value);
//							$this->sendTxt('滚雪球优惠码验证成功，您可用此凭证在门店以折扣价购买油品。');
//						}
//					}else{
//						tellgoto('代码不存在','cheap_code.php');
//					}
//				}
//				if(is_numeric($Content) && strlen($Content)==16){
//					//正常获得16位数字产品编码
//					$user=$db->ig2_want('mae_user','role_type=2 and openid="'.$this->fromUsername.'"');
//					if(!$user){
//						//扫描人不是店员
//						$this->sendTxt('只有店员可以验证');
//					}
//					$role=$db->ig2_want('mae_role','is_delete=0 and uid='.$user['id']);
//					if(!$role){
//						//扫描人不是店员
//						$this->sendTxt('只有店员可以验证');
//					}
//					$client = new SoapClient(API_url);
//					$param = array(
//						'userID'=>API_userID,
//						'userPwd'=>API_userPwd,
//						'ip'=>$this->GetIP(),
//						'acCode'=>$Content,
//						'language'=>'zh-cn',
//						'channel'=>'21'
//					);
//					$p = $client->__soapCall('Get_ACCodeProductInfo',array('parameters' => $param));
//					$state=$p->systemState;
//					$state=substr($state,0,4);
//					switch($state){
//						case '1002':
//							//数码存在
//							$sell=$db->ig2_want('mae_sell','shell_key="'.$Content.'"');
//							if($sell){
//								//已售出
//								$this->sendTxt('此商品已售出');
//							}else{
//								//未售出
//								$reply=$p->reply;
//								$reply = simplexml_load_string($reply, 'SimpleXMLElement', LIBXML_NOCDATA);
//								if($reply->item->productid=='' && ($reply->item->productspec=='小桶(3.5L-5L)'||$reply->item->productspec=='1L-5L'||$reply->item->productspec=='4L')){
//									$reply->item->productid=550000000;
//								}
//								$pro=$db->ig2_want('mae_pro','pro_id="'.$reply->item->productid.'"');
//								$p->reply=$reply;
//								$p=json_encode($p);
//								if($pro){
//									//是活动商品
//									$co=0;
//									$succes=false;
//									while(!$succes){
//										$succes=true;
//										$id=0;
//										$db->ig2_query('BEGIN');
//										//插入销售记录
//										$result1=$db->ig2_query("insert into mae_sell (`id`,`account_id`,`shell_key`,`pro_id`,`productname`,`productspec`,`productinfo`,`uid`,`create_time`) values ('".$id."','16621','".$Content."','".$reply->item->productid."','".$reply->item->productname."','".$reply->item->productspec."','".$p."','".$user['id']."','".time()."');");
//										$succes=$succes && $result1?true:false;
//										//更新积分
//										$result2=$db->ig2_query("update mae_user set score=".($user['score']+SELLSCORE)." WHERE id=".$user['id']);
//										$succes=$succes && $result2?true:false;
//										$result3=$db->ig2_query("update mae_shop set sell_count=sell_count+1,now_month_count=now_month_count+1,quadratic=quadratic+".SELLSCORE." WHERE id=".$role['shop_id']);
//										$succes=$succes && $result3?true:false;
//										//插入心愿单
//                                        $sday=date('Y-m-',time()).'1';
//                                        $eday=date('Y-m-d',strtotime("$sday +1 month"));
//                                        $sday=strtotime($sday);
//                                        $eday=strtotime($eday);
//                                        $lastwish=$db->ig2_select("mae_wish_list","uid=".$user['id']." and create_time >= $sday and create_time < $eday");
//										if(!$lastwish){
//											$succes=$succes && $db->ig2_query("insert into mae_wish_list (`account_id`,`sell_id`,`uid`,`status`,`is_see`,`create_time`) values ('16621','".$Content."','".$user['id']."','0','0','".time()."');")?true:false;
//											$wishid=mysql_insert_id();
//										}
//										if($succes){
//											$db->ig2_query('COMMIT');
//										}else{
//											$db->ig2_query('ROLLBACK');
//										}
//										if(++$co>=100){
//											$this->sendTxt('服务器忙，请稍后再试('.$result1.'0'.$result2.'0'.$result3);
//										}
//									}
//									$this->sendTxt('验证成功，成功获得15个积分，可在个人中心查看并兑换'.($wishid?'，并可填写<a href="'.SiteUrl.'wish.php?wishid='.$wishid.'">心愿单</a>':''));
//								}else{
//									//非活动商品
//									$this->sendTxt('此商品为真，但不在活动商品之列');
//								}
//							}
//							break;
//						case '0002':
//							//数码不存在
//							$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
//							break;
//						case '003':
//							//数码不存在
//							$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
//							break;
//						case '102':
//							//数码不存在
//							$this->sendTxt('此代码不存在，请检查标签，确认代码是否正确，点击菜单重新验证');
//							break;
//						default:
//							//ip限制，ip最大值等问题
//							$this->sendTxt('查询异常');
//							break;
//					}
//					exit;
//				}
//				//未获得16位数字产品编码
//				$this->sendTxt('错误编码');
			}
		}else {
			$this->sendTxt('未知消息');
		}
	}
	
	private function sendTxt($contentStr='') {
		$textTpl = "
			<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[text]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				<FuncFlag>0</FuncFlag>
			</xml>
		";
		$time = time();
		$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, $time,  $contentStr);
		echo $resultStr;
		exit;
	}
	
	private function sendNews($title='',$des='',$picurl='',$url='') {
		$textTpl = "
			<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[news]]></MsgType>
				<ArticleCount>1</ArticleCount>
				<Articles>
					<item>
						<Title><![CDATA[%s]]></Title> 
						<Description><![CDATA[%s]]></Description>
						<PicUrl><![CDATA[%s]]></PicUrl>
						<Url><![CDATA[%s]]></Url>
					</item>
				</Articles>
			</xml> 
		";	
		$time = time();
		$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, $time, $title, $des,$picurl,$url);
		echo $resultStr;
		exit;
	}
	private function GetIP(){
		if(!empty($_SERVER["HTTP_CLIENT_IP"])){
		  $cip = $_SERVER["HTTP_CLIENT_IP"];
		}
		elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
		  $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}
		elseif(!empty($_SERVER["REMOTE_ADDR"])){
		  $cip = $_SERVER["REMOTE_ADDR"];
		}
		else{
		  $cip = "127.0.0.1";
		}
		return $cip;
	}
	private function checkSignature() {
		// you must define TOKEN by yourself
		if (!defined("TOKEN")) {
			throw new Exception('TOKEN is not defined!');
		}
		
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
				
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		
		// use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}

    // 扫码验证
    private function getScanResult($db,$openId, $validationCode) {
        $user=$db->ig2_want('mae_user','role_type=2 and openid="'.$openId.'"');
        if(!$user){
            //扫描人不是店员
            return '验证失败，只有店员可以参与扫油积分活动，您无法参与此积分活动';
        }

        $role=$db->ig2_want('mae_role','is_delete=0 and role_type=2 and uid='.$user['id']);
        if(!$role){
            //扫描人不是店员
            return '验证失败，只有店员可以参与扫油积分活动，您无法参与此积分活动';
        }

        $shop = $db->ig2_want('mae_shop','id='.$role['shop_id']);

        $xml = "<?xml version='1.0' encoding='utf-8' ?>";
        $xml .= "<Info>";
        $xml .= "<mobile>".$user['phone']."</mobile>";
        $xml .= "<store>".$shop['name']."</store>";
        $xml .= "<name>".$user['name']."</name>";
        $xml .= "</Info>";
        $client = new SoapClient(INTERFACE_URL);
        $param = array(
            'userID'=>INTERFACE_USERID,
            'userPwd'=>INTERFACE_PWD,
            'ip'=>GetIP(),
            'acCode'=>$validationCode,
            'language'=>'zh-cn',
            'channel'=>'21',
            'xml'=>$xml
        );

        $p = $client->__soapCall('Get_InfoByACCode',array('parameters' => $param));
		
        $systemState=$p->systemState;

        $reply = $p->reply;
		$this->_log($reply);
        // 油品码错误
        $sell=$db->ig2_want('mae_sell','shell_key="'.$validationCode.'"');
        $this->_log($sell);
        if ($sell) {
            return '验证失败，此油品已售，请核实后重新验证';
        }

        if ($systemState != '10020401' && $systemState != '10020402' && $systemState != '10020301') {
        	//报的是这个错误
            return '该产品因如下原因不参与积分活动。\n1.该产品出厂日期早于2015年1月1日；\n2.该产品不属于壳牌喜力系列的4L油品；\n3.非大陆地区产品；\n如有疑问请通过意见箱反馈，感谢！';
        }
        // 判断油品是否经过优惠码售出过，如果已经售出过，则不能再次售出
        /*$sell=$db->ig2_want('mae_sell','shell_key="'.$validationCode.'"');
        if ($sell) {
            return '验证失败，此油品已售，请核实后重新验证';
        }*/
		
        // 无产品信息的油码，提示无效
        $reply = simplexml_load_string($reply, 'SimpleXMLElement', LIBXML_NOCDATA);
		
		//resultmsg值为3且productid为空时,允许被积分，按照特殊分值给予积分15分
		if($reply->item->resultmsg=='3'){
			return $this->sell($db, $validationCode, 
				array('id'=>'20','account_id'=>"16621",'pro_id'=>"0000000",'pro_name_en'=>"4L00000",'pro_name_cn'=>"壳牌4L活动优惠",'short_name'=>"壳牌4L",'type'=>"",'score'=>"",'returnprice'=>""),
						$user['id'], '0000000', '壳牌4L活动优惠', '壳牌4L', json_encode($p));
		}
        if($reply->item->productid==''){
        	//$this->_log('@@@@');
            return "该产品因如下原因不参与积分活动。\n1.该产品出厂日期早于2015年1月1日；\n2.该产品不属于壳牌喜力系列的4L油品；\n3.非大陆地区产品；\n如有疑问请通过意见箱反馈，感谢！";
        }

        // 判断是否为活动产品
        $pro = $db->ig2_want('mae_pro','pro_id="'.$reply->item->productid.'"');
        if (!$pro) {
            return "该产品因如下原因不参与积分活动。\n1.该产品出厂日期早于2015年1月1日；\n2.该产品不属于壳牌喜力系列的4L油品；\n3.非大陆地区产品；\n如有疑问请通过意见箱反馈，感谢！";
        }

        // 判断销量是否达到月销量上限：N*user_sale_limit
        $shop = $db->ig2_want('mae_shop','id='.$role['shop_id']);
        $userSaleLimit = 50;
        if ($shop['user_sale_limit']) {
            $userSaleLimit = $shop['user_sale_limit'];
        }
        if ($shop['now_month_count'] >= $shop['repairman_limit'] * $userSaleLimit) {
            return '验证失败，您所处的门店的月销量已达上限';
        }

        // 判断当前用户当月是否已经销售达到店员销量上限
        $sday=date('Y-m-',time()).'1';
        $eday=date('Y-m-d',strtotime("$sday +1 month"));
        $sday=strtotime($sday);
        $eday=strtotime($eday);
        $sells=$db->ig2_select("mae_sell","uid=".$user['id']." and create_time >= $sday and create_time < $eday");
        if (count($sells) >= $userSaleLimit) {
            return '您已达到每月扫码积分上限（'.$userSaleLimit.'桶），请您在下月继续。';
        }

        return $this->sell($db, $validationCode, $pro, $user['id'], $reply->item->productid, $reply->item->productname, $reply->item->productspec, json_encode($p));
    }

    private function sell($db, $validationCode, $pro, $userId, $productId, $productName, $productSpec, $productInfo) {
        $success = true;
        $db->ig2_query('BEGIN');

        // 记录销售结果，如果已经有使用优惠码的销售记录，直接在此记录上追加
        $score = 15;
        $result1 = false;

        // 取得商品型号，获得应该得到的积分
        $shortName = explode(' ', $pro['short_name']);
        if ($shortName) {
            $typeName = $shortName[1];
            $proActivity = $db->ig2_want("mae_pro_activity","typename='".$typeName."'");
            if ($proActivity) {
                $score = $proActivity['score'];
            }
        }

        // 有简称使用简称
        if ($pro['short_name']) {
            $productName = $pro['short_name'];
        }
        $id=rand(1,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
        $insertSellSql = "insert into mae_sell (`id`,`account_id`,`shell_key`,`pro_id`,`productname`,`productspec`,`productinfo`,`uid`,`create_time`,`score`) values (";
        $insertSellSql .= $id;
        $insertSellSql .= ",16621";
        $insertSellSql .= ",'".str_replace ( "'", "''",$validationCode)."'";
        $insertSellSql .= ",'".str_replace ( "'", "''",$productId)."'";
        $insertSellSql .= ",'".str_replace ( "'", "''",$productName)."'";
        $insertSellSql .= ",'".str_replace ( "'", "''",$productSpec)."'";
        $insertSellSql .= ",'".str_replace ( "'", "''",$productInfo)."'";
        $insertSellSql .= ",".$userId;
        $insertSellSql .= ",".time();
        $insertSellSql .= ",".$score;
        $insertSellSql .= ");";
        $result1=$db->ig2_query($insertSellSql);

        $success=$success && $result1?true:false;

        // 更新积分
        $result1 = false;
        if ($success) {
            $result1=$db->ig2_query("update mae_user set score=score+".$score." WHERE id=".$userId);
            $success=$success && $result1?true:false;
        }

        // 更新销量
        $result1 = false;
        if ($success) {
            $role=$db->ig2_want('mae_role','is_delete=0 and role_type=2 and uid='.$userId);
            $result1=$db->ig2_query("update mae_shop set sell_count=sell_count+1,now_month_count=now_month_count+1,quadratic=quadratic+".round($score/1)." WHERE id=".$role['shop_id']);
            $success=$success && $result1?true:false;
        }

        // 如果店铺在达标有奖分组内，并且所属店铺的销量达到了当月奖励指标，则发放奖励积分，并记录下月需提醒的浮层日志
        $activitySql = "SELECT rpa.* FROM mae_reach_prize_activity rpa";
        $activitySql .= " INNER JOIN mae_rel_reach_prize_activity_group rrpag ON rpa.id = rrpag.activityid";
        $activitySql .= " INNER JOIN mae_group g ON g.id = rrpag.groupid";
        $activitySql .= " INNER JOIN mae_rel_group_shop rgs ON rgs.groupid = g.id";
        $activitySql .= " INNER JOIN mae_shop s ON s.id = rgs.shopid";
        $activitySql .= " WHERE s.id = ".$role['shop_id']." AND rpa.status = 1 AND rpa.starttime <= ".time()." AND rpa.endtime >= ".time();
        $activitySql .= " LIMIT 0,1";
        $activity = $db->ig2_query_select($activitySql);

        if ($activity) {
            $result1 = false;
            $nowtime=date('Y-m-01', strtotime(date("Y-m-d")));
            $currentMonth = date('m', strtotime($nowtime));
            $currentYear = date('Y', strtotime($nowtime));

            $shop = $db->ig2_want('mae_shop', 'id = '.$role['shop_id']);
            $growthRate = $db->ig2_want('mae_growth_rate', 'shopid = '.$role['shop_id'].' AND statyear = "'.$currentYear.'"');
            if ($growthRate && $growthRate['purpose'] > 0 && $growthRate['addscore'] > 0 && $shop['now_month_count'] >= $growthRate['purpose']) {
                $encourageLog = $db->ig2_want('mae_sell_encourage_log', 'shopid = '.$role['shop_id'].' AND statyear = "'.$currentYear.'", AND statmonth = "'.$currentMonth.'"');
                if (!$encourageLog) {
                    $result1=$db->ig2_query("update mae_shop set quadratic=quadratic+".$growthRate['addscore']." WHERE id=".$role['shop_id']);
                    $success=$success && $result1?true:false;

                    if ($success) {
                        $result1 = false;
                        $result1=$db->ig2_query("INSERT INTO mae_sell_encourage_log(shopid, purpose, addscore, statyear, statmonth) VALUES (".$role['shop_id'].", ".$growthRate['purpose'].", ".$growthRate['addscore'].", '".$currentYear."', '".$currentMonth."')");
                        $success=$success && $result1?true:false;
                    }
                }
            }
        }
        // 插入心愿单
        // 在心愿单活动分组内的才插入心愿单
        $result1 = false;
        $wishid = 0;
        if ($success) {
            $activitySql = "SELECT wa.* FROM mae_wish_activity wa";
            $activitySql .= " INNER JOIN mae_rel_wish_activity_group rwag ON rwag.activityid = wa.id";
            $activitySql .= " INNER JOIN mae_group g ON g.id = rwag.groupid";
            $activitySql .= " INNER JOIN mae_rel_group_shop rgs ON rgs.groupid = g.id";
            $activitySql .= " INNER JOIN mae_shop s ON s.id = rgs.shopid";
            $activitySql .= " WHERE s.id = ".$role['shop_id']." AND wa.status = 1 AND wa.starttime <= ".time()." AND wa.endtime >= ".time();
            $activity = $db->ig2_query_select($activitySql);

            // 如果在心愿单活动分组内，则执行插入心愿单逻辑
            if ($activity) {
                $sday=date('Y-m-',time()).'1';
                $eday=date('Y-m-d',strtotime("$sday +1 month"));
                $sday=strtotime($sday);
                $eday=strtotime($eday);
                $lastwish=$db->ig2_select("mae_wish_list","uid=".$userId." and create_time >= $sday and create_time < $eday");
                if(!$lastwish){
                    $result1 = $db->ig2_query("insert into mae_wish_list (`account_id`,`sell_id`,`uid`,`status`,`is_see`,`create_time`) values ('16621','".$validationCode."','".$userId."','0','0','".time()."');");
                    $success=$success && $result1?true:false;
                    $wishid=mysql_insert_id();
                }
            }
        }
		$xml = "<?xml version='1.0' encoding='utf-8' ?>";
        $xml .= "<Info>";
        $xml .= "<mobile>".$user['phone']."</mobile>";
        $xml .= "<store>".$shop['name']."</store>";
        $xml .= "<name>".$user['name']."</name>";
        $xml .= "</Info>";
        $client = new SoapClient(INTERFACE_URL);
        $param = array(
            'userID'=>INTERFACE_USERID,
            'userPwd'=>INTERFACE_PWD,
            'ip'=>GetIP(),
            'acCode'=>$validationCode,
            'language'=>'zh-cn',
            'channel'=>'21',
            'xml'=>$xml
        );

        $p = $client->__soapCall('Get_InfoByACCode',array('parameters' => $param));
		//$this->_log($p);
        $systemState=$p->systemState;
        $reply = $p->reply;
		$reply = simplexml_load_string($reply, 'SimpleXMLElement', LIBXML_NOCDATA);
		 
		if($reply->item->resultmsg=='3'){
			if ($success) {
            $db->ig2_query('COMMIT');
            return '验证成功，由于部分产品缺少生产信息，故统一给予15个积分奖励，您可在个人中心查看并兑换，敬请谅解';
        } else {
            $db->ig2_query('ROLLBACK');
            return '服务器忙，请稍后再试';
        }
		}
		
        if ($success) {
            $db->ig2_query('COMMIT');
            return '验证成功，成功获得'.$score.'个积分，可在个人中心查看并兑换'.($wishid?'，并可填写<a href="'.SiteUrl.'wish.php?wishid='.$wishid.'">心愿单</a>':'');
        } else {
            $db->ig2_query('ROLLBACK');
            return '服务器忙，请稍后再试';
        }
		
    }

    // 红包推送
    private function pushRedPocket($db, $openId) {
        // 只有店长和店员可以兑换红包
        $user = $db->ig2_want('mae_user','openid="'.$openId.'" AND role_type in (1,2) AND is_delete=0');
        if (!$user) {
            $this->sendTxt("对不起，只有店长和机修工才能兑换红包");
        }

        $now = time();
        $redPocketActivity = $db->ig2_want('mae_red_pocket_activity','status=1 AND starttime <= '.$now.' AND endtime >= '.$now);
        // 如果没有开启的红包活动，报错;
        if (!$redPocketActivity) {
            $this->sendTxt("待活动开始后，通过个人中心页面提示");
        }

        // 当前员工是否在活动组内
        $groupSql = " SELECT g.* FROM mae_group g";
        $groupSql .= " INNER JOIN mae_rel_red_pocket_activity_group mrrpag ON mrrpag.groupid = g.id";
        $groupSql .= " INNER JOIN mae_red_pocket_activity mrpa ON mrpa.id = mrrpag.activityid";
        $groupSql .= " INNER JOIN mae_rel_group_shop mrgs ON mrgs.groupid = g.id";
        $groupSql .= " INNER JOIN mae_shop s ON s.id = mrgs.shopid AND s.status = 1";
        $groupSql .= " INNER JOIN mae_role r ON r.shop_id = s.id AND r.is_delete = 0";
        $groupSql .= " INNER JOIN mae_user u ON u.id = r.uid AND u.is_delete = 0";
        $groupSql .= " WHERE u.id = ".$user['id']." AND mrpa.id = ".$redPocketActivity['id'];

        $group = $db->ig2_query_select($groupSql);

        if (!$group) {
            $this->sendTxt("待活动开始后，通过个人中心页面提示");
        }

        $this->sendNews("红包来了","壳牌喜力汽车专家",SiteUrl."images/hongbaocome1.jpg",SiteUrl."hongbao.php");
    }
}

?>